package cn.wolfcode.web.controller;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Notice;
import cn.wolfcode.domain.Permission;
import cn.wolfcode.exception.BusinessException;
import cn.wolfcode.qo.JsonResult;
import cn.wolfcode.qo.NoticeQueryObject;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.INoticeService;
import cn.wolfcode.util.UserContext;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.naming.Context;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
public class LoginController {
    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private INoticeService noticeService;
    @RequestMapping("/empLogin")
    @ResponseBody
    public JsonResult empLogin(String username, String password, HttpSession httpSession){
        JsonResult jsonResult = new JsonResult();
        Employee login = new Employee();
        try{
            login = employeeService.login(username, password);
        }catch (BusinessException e){
            jsonResult.setMsg(e.getMessage());
            jsonResult.setSuccess(false);
        }
//        如果不报异常就是登陆成功,这个时候需要存Session;
        httpSession.setAttribute(UserContext.USER_IN_SESSION,login);
//        获取到权限,并将它存入session
        List<Permission> permissions =  employeeService.getPermissions(login.getId());
        httpSession.setAttribute(UserContext.PERMISSION_IN_SESSION,permissions);

//        将map信息放进session;
        NoticeQueryObject qo = new NoticeQueryObject();
        qo.setRead(false);
        qo.setPageSize(0);
        PageInfo<Notice> pageInfo = noticeService.query(qo);

        UserContext.setNoticeMessage(pageInfo);
        return jsonResult;
    }

    @RequestMapping("/logout")
    public String logout(HttpSession httpSession){
        httpSession.invalidate();
        return "redirect:/login.html";
    }

    @RequestMapping("/noPermission")
    public String noPermission(){
        return "/common/nopermission";
    }

    @RequestMapping("/error")
    public String error(){
        return "/common/error";
    }
}
